<template>
	<view class="app-content">
		<u-transition :show="!loading" mode="fade-right">
		<!-- 导航 -->
		<view>
			<u-navbar :title="title" :leftIconSize="0" titleStyle="color:#fff" :bgColor="bgColor" v-if="!loading" :fixed="true" :placeholder="true">
				<view slot="left">
					<view class="u-nav-slot" v-if="daohang.list.length<=0">
						<u-icon color="#fff" @click="tofanhui()" name="arrow-left" size="19" ></u-icon>
						<u-line direction="column" :hairline="false" length="16" margin="0 8px" ></u-line>
						<u-icon color="#fff" @click="toindex()" name="home" size="20" ></u-icon>
					</view>
				</view>
			</u-navbar>
		</view>
		<view class="xiangqing">
			<view class="login_heard" :style="'background-color:'+bgColor+';'"></view>
			<view class="login_title">
				<view class="login_title_center">
					<view class="login_title_center_tabs">
						<u-tabs :list="[{name:'账号注册'}]" :activeStyle="{ color:bgColor, fontWeight: 'bold',transform: 'scale(1.05)' }" :lineColor="bgColor" ></u-tabs>
					</view>
				</view>
			</view>
			<view class="login_center" >
				<u--form
					labelPosition="left"
					:model="registerForm"
					:rules="rules"
					ref="rgForm"
					labelWidth="180rpx"
					:labelStyle="{color:bgColor}"
				>
					<u-form-item
						required
						label="用户名"
						prop="uname"
						borderBottom
						
					>
						<u--input
							v-model="registerForm.uname"
							border="none"
							clearable
							@blur="inputBlur('uname')"
						></u--input>
					</u-form-item>
					<u-form-item
						label="用户昵称"
						prop="nickName"
						borderBottom
						
					>
						<u--input
							v-model="registerForm.nickName"
							border="none"
							clearable
						></u--input>
					</u-form-item>
					<u-form-item
						label="图形验证码"
						prop="code"
						borderBottom
						required
					>
						<!-- #ifndef APP-NVUE -->
						<u-input 
							border="none"
							placeholder="请输入图形验证码"
							:placeholderStyle="'font-size: 25rpx;color:'+bgColor+';'"
							v-model="registerForm.code"
							clearable>
						<!-- #endif -->
						<!-- #ifdef APP-NVUE -->
						<u--input 
								border="none"
								placeholder="请输入图形验证码"
								:placeholderStyle="'font-size: 25rpx;color:'+bgColor+';'"
								v-model="registerForm.code"
								clearable>
						<!-- #endif -->
							<template slot="suffix">
								<img @click="getshijiancuo()" :src="config.checkcode+'/'+codeSjc" style="width: 80px;">
							</template>
						<!-- #ifndef APP-NVUE -->
						</u-input>
						<!-- #endif -->
						<!-- #ifdef APP-NVUE -->
						</u--input>
						<!-- #endif -->
					</u-form-item>
					<u-form-item
						label="手机号码"
						prop="phone"
						borderBottom
						required
					>
						<u--input
							border="none"
							placeholder="请输入您的手机号"
							:placeholderStyle="'font-size: 25rpx;color:'+bgColor+';'"
							clearable
							v-model="registerForm.phone"
						></u--input>
					</u-form-item>
					<u-form-item
						label="短信验证码"
						prop="smsCode"
						borderBottom
						required
						v-if="registerForm.phone&&config.isSmsLogin=='1'"
					>
						<!-- #ifndef APP-NVUE -->
						<u-input 
							border="none"
							placeholder="请输入短信验证码"
							:placeholderStyle="'font-size: 25rpx;color:'+bgColor+';'"
							v-model="registerForm.smsCode"
							shape="circle">
						<!-- #endif -->
						<!-- #ifdef APP-NVUE -->
						<u--input 
								border="none"
								placeholder="请输入短信验证码"
								:placeholderStyle="'font-size: 25rpx;color:'+bgColor+';'"
								v-model="registerForm.smsCode"
								shape="circle">
						<!-- #endif -->
							<template slot="suffix">
								<u-code
									ref="uCode"
									@change="smsCodeChange"
									:keepRunning="true"
									seconds="60"
									changeText="X秒重新获取"
								></u-code>
								<u-button
									@tap="getSmsCode"
									:text="codeTips"
									:color="bgColor"
									size="mini"
								></u-button>
							</template>
						<!-- #ifndef APP-NVUE -->
						</u-input>
						<!-- #endif -->
						<!-- #ifdef APP-NVUE -->
						</u--input>
						<!-- #endif -->
					</u-form-item>
					<u-form-item
						label="登录密码"
						prop="password"
						borderBottom
						required
					>
						<u--input
							border="none"
							placeholder="请输入登录密码"
							:placeholderStyle="'font-size: 25rpx;color:'+bgColor+';'"
							clearable
							type="password"
							password
							v-model="registerForm.password"
						></u--input>
					</u-form-item>
					<u-form-item
						label="重复密码"
						prop="cfpassword"
						borderBottom
						required
					>
						<u--input
							border="none"
							placeholder="请重复输入登录密码"
							:placeholderStyle="'font-size: 25rpx;color:'+bgColor+';'"
							clearable
							type="password"
							password
							v-model="registerForm.cfpassword"
						></u--input>
					</u-form-item>
				</u--form>
			</view>
			<view class="registerBtn">
				<u-button :color="bgColor" :disabled="btnLoading" :loading="btnLoading" loadingText="注册中" text="注册" @click="registerBtn()" shape="circle"></u-button>
			</view>
			<!-- 协议和规则 -->
			<view class="xieyi">
				<view class="xieyi_false" v-if="!isXieyi" @click="xieyiBtn" :style="'border-color:'+bgColor+';'"></view>
				<view class="xieyi_true" v-if="isXieyi" @click="xieyiBtn">
					<u-icon name="checkmark-circle-fill" :color="bgColor" size="34rpx"></u-icon>
				</view>
				<view class="xieyi_text" @tap="xieyiBtn">
					同意{{config.codeName}}的<view class="xieyi_link" :style="'color:'+bgColor+';'" @tap.stop="tourl(config.yszcUrl)">隐私政策</view>和<view class="xieyi_link" :style="'color:'+bgColor+';'" @tap.stop="tourl(config.yhxyUrl)">用户协议</view>
				</view>
			</view>
		</view>
		</u-transition>
		<u-tabbar v-if="daohang.list.length>0" :zIndex="999" :border="daohang.navi_set.border=='1'?true:false" :value="daohang.naviKey" :activeColor="daohang.navi_set.active_color" :inactiveColor="daohang.navi_set.inactive_color">
			<u-tabbar-item v-for="(item,index) in daohang.list" :badge="item.badge" :key="index" :text="item.text" :icon="daohang.naviKey==index?item.selectedIconPath:item.iconPath" @click="tabClick(item,index)" ></u-tabbar-item>
		</u-tabbar>
		<u-no-network @disconnected="disconnected" ></u-no-network>
		<u-toast ref="uToast" />
		<view class="km_loading" v-if="loading">
			<image src="@/static/loading_3.gif" mode=""></image>
		</view>
	</view>
</template>

<script>
	import {
		wappConfig
	} from "@/api/api.js";
	import {
		userApi,getuserinfo
	} from "@/api/user.js";
	export default {
		data() {
			return {
				title: '注册',
				bgColor:"#5064eb",
				loading:true,
				config:{},
				pagePath:'/pages/login/register',
				daohang:{
					list:[],
					naviKey:0,
					navi_set:{
						active_color: "#34C083",
						height: 100,
						inactive_color: "#757575",
					}
				},
				user:{},
				registerForm:{
					uname:"",
					nickName:"",
					code:"",
					smsCode:"",
					password:"",
					cfpassword:"",
					phone:"",
				},
				rules: {
					'uname': [
						{
							type: 'string',
							required: true,
							message: '请填写用户名,用来登录使用的',
							trigger: ['blur', 'change']
						},
						// 正则判断为字母或数字
						{
							pattern: /^[a-zA-Z0-9_-]{4,16}$/,
							// 正则检验前先将值转为字符串
							transform(value) {
								return String(value);
							},
							message: '4到16位（字母)(数字，下划线，减号）',
							trigger: ['blur', 'change']
						},
					],
					'code': [
						{
							required: true, 
							message: '请输入图形验证码',
							trigger: ['change','blur'],
						},
					],
					'smsCode': [
						{
							required: true, 
							message: '请输入短信验证码',
							trigger: ['change','blur'],
						},
					],
					'phone': [
						{
							required: true, 
							message: '请输入手机号',
							trigger: ['change','blur'],
						},
						{
							// 自定义验证函数，见上说明
							validator: (rule, value, callback) => {
								// 上面有说，返回true表示校验通过，返回false表示不通过
								// uni.$u.test.mobile()就是返回true或者false的
								return uni.$u.test.mobile(value);
							},
							message: '手机号码不正确',
							// 触发器可以同时用blur和change
							trigger: ['change','blur'],
						}
					],
					'password': [
						{
							required: true, 
							message: '请输入密码',
							trigger: ['change','blur'],
						},
						{
							min: 8,
							max: 18,
							message: '密码长度为8-18位',
							trigger: ['change','blur'],
						},
						{
							pattern: /^(?![^a-zA-Z]+$)(?!\D+$)/,
							// 正则检验前先将值转为字符串
							transform(value) {
								return String(value);
							},
							message: '密码必须由字母、数字组成，区分大小写',
							trigger: ['blur', 'change']
						},
					],			
					'cfpassword': [
						{
							required: true, 
							message: '请输入密码',
							trigger: ['change','blur'],
						},
						{
							// 自定义验证函数，见上说明
							validator: (rule, value, callback) => {
								// 上面有说，返回true表示校验通过，返回false表示不通过
								// uni.$u.test.mobile()就是返回true或者false的
								let rt=false;
								if(value===this.registerForm.password){
									rt =true;
								}
								return rt;
							},
							message: '两次输入的密码不一样',
							// 触发器可以同时用blur和change
							trigger: ['change','blur'],
						}
					],					
				},
				codeTips: '',
				codeSjc:"",
				btnLoading:false,
				isXieyi:false,
			}
		},
		components: {
		},
		onReady() {
			//如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
			//#ifdef MP
			this.$refs.rgForm.setRules(this.rules)
			//#endif
		},
		onLoad() {
			this.getconfig();
		},
		onShow() {
			if (this.$store.getters.isLogin) {
				this.getuser();
			}
		},
		methods: {
			toxyzc(e){
				console.log(e)
			},
			xieyiBtn(){
				this.isXieyi=!this.isXieyi;
			},
			registerBtn(){
				let t=this;
				if(!t.isXieyi){
					t.$refs.uToast.show({
						type: 'error',
						message:'请先同意用户协议和隐私政策'
					})
					return false;
				}
				t.$refs.rgForm.validate().then(res => {
					console.log(res)
					t.btnLoading=true;
					let dt={
						uname:uni.$u.trim(t.registerForm.uname),
						nickName:uni.$u.trim(t.registerForm.nickName),
						phone:uni.$u.trim(t.registerForm.phone),
						smsCode:uni.$u.trim(t.registerForm.smsCode),
						password:uni.$u.trim(t.registerForm.password),
						cfpassword:uni.$u.trim(t.registerForm.cfpassword),
						os:t.$store.getters.systeminfo
					}
					userApi('register',dt,'post',true).then(res=>{
						console.log(res)
						t.$refs.uToast.show({
							type: res.data.type?res.data.type:'success',
							message:res.data.msg?res.data.msg:res.msg?res.msg:'操作成功'
						})
						setTimeout(() => {
							t.tofanhui();
							t.btnLoading=false;
						}, 2000);
					}).catch(errors => {
						t.btnLoading=false;
						console.log(errors)
					})
				}).catch(errors => {
					console.log(errors)
					t.$refs.uToast.show({
						type: 'error',
						message:errors[0].message?errors[0].message:'有必填项未填写'
					})
				})
			},
			smsCodeChange(text) {
			  this.codeTips = text;
			},
			getSmsCode() {
				let t=this;
				t.$refs.rgForm.validateField('code',(res)=>{
					console.log((res))
					if(res[0]){
						t.$refs.uToast.show({
							type: 'error',
							message:res[0].message?res[0].message:'有必填项未填写'
						})
					}else{
						t.$refs.rgForm.validateField('phone',(res)=>{
							console.log((res))
							if(res[0]){
								t.$refs.uToast.show({
									type: 'error',
									message:res[0].message?res[0].message:'有必填项未填写'
								})
							}else{
								if (t.$refs.uCode.canGetCode) {
								  // 模拟向后端请求验证码
								  uni.showLoading({
								    title: '正在获取验证码'
								  })
								  let dt={
									  phone:uni.$u.trim(t.registerForm.phone),
									  code:uni.$u.trim(t.registerForm.code),
									  codetype:uni.$u.trim(t.codeSjc),
								  }
								  t.getSendSmsCode(dt);
								} else {
								  uni.$u.toast('倒计时结束后再发送');
								}
							}
						})
					}
				})
			},
			getSendSmsCode(dt){
				if(!dt){
					return false;
				}
				userApi("sendSmsCode",dt,'post',true).then(res=>{
					console.log(res)
					uni.hideLoading();
					// 这里此提示会被this.start()方法中的提示覆盖
					uni.$u.toast('验证码已发送');
					// 通知验证码组件内部开始倒计时
					t.$refs.uCode.start();
				}).catch(errors => {
					uni.hideLoading();
					console.log(errors)
				})
			},
			getshijiancuo(){
				let sjc=new Date().getTime();
				this.codeSjc=sjc+''+uni.$u.random(1000, 9999);
			},
			inputBlur(e){
				let t = this;
				if(e=='uname'){
					if(t.registerForm.nickName==""){
						t.registerForm.nickName=t.registerForm.uname
					}
				}
			},
			retry(){
				this.getconfig();
			},
			tourl(e){
				console.log(e)
				if(!e){
					return true;
				}
				if(e==this.pagePath){
					return true;
				}
				uni.navigateTo({
					url:e,
					fail(error) {
						console.log(error)
						uni.showToast({
							title:"跳转出错",
							icon:"none"
						})
					}
				})
			},
			tofanhui(){
				console.log(1)
				uni.navigateBack({
					delta: 1,
					fail(){
						 uni.reLaunch({
							 url: '/pages/index/index'
						 });
					}
				})
			},
			toindex(){
				uni.reLaunch({
					url: '/pages/index/index'
				});
			},
			// 切换导航
			tabClick(e,i){
				if(this.daohang.naviKey!=i){
					uni.reLaunch({
						url:e.pagePath,
						fail(err) {
							uni.showModal({
								content:err.errMsg,
								title:"错误提示",
								showCancel:false,
								fail(r) {
									console.log(r)
								}
							})
							console.log(err)
						}
					})
				}
				
			},
			getconfig(){
				let that=this;
				wappConfig({pagePath:that.pagePath}).then(e=>{
					console.log(e)
					that.daohang=e.data.naviList;
					that.config=e.data;
					if(!that.codeSjc){
						if(e.data.isCode=='1'){
							that.getshijiancuo();
						}
					}
					if(e.data.loginThemeColor){
						that.bgColor=e.data.loginThemeColor;
					}
					that.loading=false;
				})
				.catch(res => {
					console.log(res)
					uni.showModal({
						content:res.msg?res.msg:res?res:"获取配置文件失败",
						title:"提示",
						showCancel:false
					})
					that.loading=false;
				});
			},
			getuser(){
				getuserinfo(this.$store.getters.uid).then(res=>{
					console.log(res)
					this.user=res.data;
				}).catch(e=>{
					//TODO handle the exception
					console.log(e)
				})
			},
		}
	}
</script>

<style lang="scss">
	.xiangqing{
		.xieyi{
			width: 80%;
			margin: 0 auto;
			margin-top:50rpx;
			&_true{
				display: inline-block;
				vertical-align: bottom;
			}
			&_false{
				display: inline-block;
				width: 30rpx;
				height: 30rpx;
				border-radius: 50%;
				border:1px solid #fff;
				vertical-align: bottom;
			}
			&_text{
				display: inline-block;
				margin-left:10rpx;
			}
			&_link{
				display: inline-block;				
			}
		}
		.login_heard{
			height: 250rpx;
			background-color: #2979ff;
		}
		.login_title{
			height: 10rpx;
			position: relative;
			&_center{
				position: absolute;
				top:-150rpx;
				left: 50%;
				width: 90%;
				margin-left: -45%;
				min-height: 160rpx;
				border-radius: 18rpx 18rpx 0 0;
				background-color: #fff;
				&_tabs{
					margin: 20rpx;
				}
			}
		}
		.login_center{
			width: 80%;
			margin: 0 auto;
			&_input{
				background-color: rgba(80, 100, 235, 0.1);
				padding: 10rpx 30rpx;
				border-radius: 120rpx;
			}
		}
		.registerBtn{
			width: 80%;
			margin: 0 auto;
			margin-top: 100rpx;
		}
	}
</style>
